<template>
  <div>
    <div class="box">
      关爱任务设置
      <FormPanel ref="formPanel" :cols="3" :labelWidth="110" :list="formList" :formType="type" :isSubmitBtn="false" style="margin-top: 20px" @formChange="formChangeHandle" />
    </div>
    <div class="box">
      关爱对象范围
      <FormPanel ref="careObjPanel" :cols="3" :labelWidth="110" :list="careObject" :formType="type" :isSubmitBtn="false" style="margin-top: 20px" @formChange="formChangeHandle" />
    </div>
    <div class="box">
      关爱人员设置
      <FormPanel ref="carUserPanel" :cols="4" :labelWidth="110" :list="careEmp" :formType="type" :isSubmitBtn="false" style="margin-top: 20px" @formChange="formChangeHandle" />
    </div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog(false)">取 消</el-button>
      <el-button v-if="type !== 'show'" type="primary" @click="saveDialog">{{ btnText }}</el-button>
    </div>
  </div>
</template>
<script>
import { getCareTaskListById, addCareTaskList, editCareTaskList, getTemplateConf, getUserByOrg, pageTemplateConfs } from '@/api/customerRepair/visitRules/careTask2';
import { getBrandList, getSeriesList, getModelList } from '@/api/common/cars/masterDataCars';
import { queryCareTypes, templateType } from '@/api/customerRepair/visitRules/SMSTemplate2';
import { queryQuestionnaireByType } from '@/api/customerRepair/visitRules/questionnaireMake2';
import { getUserInfoByRole, getUserInfo } from '@/api/customerRepair/visitRules/careTaskSearch2';
import { dictionary } from '@/utils/dictMixin';
import { parseTime } from '@/utils/index';

export default {
  name: 'CareTaskPanel',
  components: {},
  mixins: [dictionary],
  props: {
    type: {
      type: String,
      default: 'add'
    },
    recordVersion: String,
    carePlanId: {
      type: String,
      default: ''
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.conf = { add: '保 存', edit: '修 改' };
    this.saveData = null;
    return {
      formList: this.createFormList(),
      careObject: [],
      brandList: [],
      seriesList: [],
      modelList: [],
      careTypes: [],
      userList: [],
      smsTemplateList: [],
      questionnaireList: [],
      seriesIndex: 0,
      modelIndex: 0,
      brandId: '',
      seriesId: '',
      modelId: '',
      careEmp: this.createCareEmp()
    };
  },
  computed: {
    btnText() {
      return this.conf[this.type];
    }
  },
  created() {
    this.init();
    this.initBrandList();
  },
  methods: {
    init() {
      if (this.type != 'add') {
        getCareTaskListById(this.carePlanId).then(res => {
          if (res.resultCode == 200) {
            // 初始化各种下拉框值
            this.createCareObject(res.data.careTypeCode, false, res.data.careWay, res.data.returnVisitContent);
            // 触发模板类型变更事件
            this.changeTemplateType(res.data.careWay);
            // 初始化关爱数据
            this.formList.forEach(x => {
              x.initialValue = res.data[x.fieldName];
            });

            // 初始化关爱人员设置数据
            this.careEmp.forEach(x => {
              x.initialValue = res.data[x.fieldName];
            });
            this.careEmp[0].initialValue = res.data['careEmpType'];
            let empIds = res.data['employeeIds'];
            if (empIds && empIds != '' && empIds != null) {
              let ids = [];
              let employeeIds = empIds.split(',');
              for (let i = 0; i < employeeIds.length; i++) {
                ids.push(parseInt(employeeIds[i]));
              }
              this.careEmp[1].initialValue = ids;
            }

            let param = {
              billId: res.data.carePlanId,
              billType: 10421031,
              confCode: res.data.careTypeCode
            };

            let careWay = this.filterDict(res.data['careWay'] + '', '1587');
            this.formList[3].itemList = careWay;

            // 获得关爱对象范围
            pageTemplateConfs(param).then(res => {
              // 生成关爱对象范围
              this.initCareObj(res.data, this);
              // 关爱对象范围赋值
              this.careObject.forEach(obj => {
                res.data.forEach(row => {
                  if (row.confId == obj.paramId) {
                    let val = this.getInitialValue(row.value1, row.value2, row.fieldName, row.dataType);
                    obj.initialValue = val;
                  }
                });
              });
            });
          } else {
            this.$message.error('获取关爱计划生成明细失败!');
            return;
          }
        });
      }
      // 初始化关爱人员选择列表
      getUserInfo().then(res => {
        if (res.resultCode == 200) {
          let param = {
            companyId: res.data.userInfo.companyId,
            positionCode: 10061015
          };
          getUserInfoByRole(param).then(res => {
            if (res.resultCode == 200) {
              this.careEmp[1].itemList = res.data.map(x => ({ value: x.userId, text: x.employeeName }));
            } else {
              this.$message.error('获取关爱人员列表失败!');
            }
          });
        } else {
          this.$message.error('获取当前登录用户信息失败!');
        }
      });
      queryCareTypes().then(res => {
        if (res.resultCode == 200) {
          this.careTypes = res.data;
        } else {
          this.$message.error('获取关爱类型信息失败!');
          return;
        }
      });
    },
    // 初始化品牌下拉数据用来在关爱对象范围有品牌车系车型时级联选择
    initBrandList() {
      getBrandList().then(res => {
        if (res.resultCode == 200) {
          this.brandList = res.data.map(x => ({ value: x.brandId, text: x.brandName }));
        }
      });
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '计划编号',
          fieldName: 'planNo',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '关爱类型',
          fieldName: 'careTypeCode',
          placeholder: '请选择',
          itemList: this.createDictList('1572'),
          rules: [{ required: true, message: '请选择关爱类型', trigger: 'blur' }],
          change: val => {
            this.createCareObject(val, true, null, null);
          }
        },
        {
          type: 'INPUT',
          label: '关爱名称',
          fieldName: 'careName',
          initialValue: '',
          rules: [{ required: true, message: '请填写关爱名称', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '模板类型',
          fieldName: 'careWay',
          itemList: this.createDictList('1587'),
          change: val => {
            this.changeTemplateType(val);
          }
        },
        {
          type: 'SELECT',
          label: '模板名称',
          fieldName: 'returnVisitContent',
          disabled: true,
          itemList: []
        },
        {
          type: 'SELECT',
          label: '基准日期',
          fieldName: 'baseDateCode',
          disabled: true,
          itemList: this.createDictList('1590')
        },
        {
          type: 'DATE',
          label: '基准日期',
          fieldName: 'specialHoliday'
        },
        {
          type: 'SELECT',
          label: '距基准日期',
          disabled: true,
          fieldName: 'baselineCode',
          itemList: this.createDictList('1589')
        },
        {
          type: 'INPUT',
          label: '基准前后天数',
          fieldName: 'baseDateDays',
          placeholder: '距基准日期?天产生任务'
        },
        {
          type: 'INPUT',
          label: '任务执行时间',
          fieldName: 'completeDaysAfterTask',
          placeholder: '产生任务?天内需要关爱',
          rules: [{ required: true, message: '请填写任务执行时间', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '是否启用',
          disabled: true,
          initialValue: 10041002,
          fieldName: 'whetherEnable',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '执行周期',
          initialValue: 15881001,
          disabled: true,
          fieldName: 'executeCycle',
          itemList: this.createDictList('1588')
        },
        {
          type: 'INPUT',
          label: '产生任务',
          placeholder: '天',
          disabled: true,
          selfCols: 2,
          fieldName: 'smsDaysAfterTask'
        },
        {
          type: 'TIME_SELECT',
          label: '后',
          disabled: true,
          fieldName: 'smsSendTime',
          placeholder: '发送短信'
        }
      ];
    },
    createCareObject(val, flag, careWay, returnVisitContent) {
      // 如果关爱类型是特殊假日关怀则基准日期变为日期选择控件
      if (val == 15721005) {
        this.formList[5].hidden = true;
        this.formList[6].hidden = false;
      } else {
        this.formList[5].hidden = false;
        this.formList[6].hidden = true;
      }

      let self = this;
      // flag--是否要生成关爱对象范围
      if (flag) {
        getTemplateConf(val).then(res => {
          if (res.resultCode == 200) {
            let record = res.data;
            this.initCareObj(record, self);
          } else {
            this.$message.error('获取对象范围失败!');
            return;
          }
        });
      }

      for (let i = 0; i < this.careTypes.length; i++) {
        if (this.careTypes[i].careTypeCode === val) {
          let careWay = this.filterDict(this.careTypes[i].careTypeRelationInVO.careWay.toString(), '1587');
          this.formList[3].itemList = careWay;
          this.formList[3].initialValue = '';
          this.formList[7].initialValue = this.careTypes[i].careTypeRelationInVO.baselineCode;
          this.formList[5].initialValue = this.careTypes[i].careTypeRelationInVO.baseDateCode;
        }
      }

      // 获取短信模板下拉数据
      templateType({ smsTemplateType: val }).then(res => {
        if (res.resultCode == 200) {
          this.smsTemplateList = res.data.map(x => ({ value: x.smsTemplateId, text: x.smsTemplateName }));
          if (careWay && careWay != null && careWay == 15871002) {
            this.formList[4].itemList = this.smsTemplateList;
            // 修改时设置短信模板选中值
            if (returnVisitContent && returnVisitContent != null) {
              this.formList[4].initialValue = parseInt(returnVisitContent);
            }
          }
        } else {
          this.$message.error('获取短信模板失败!');
          return;
        }
      });

      // 获取问卷模板下拉数据
      queryQuestionnaireByType({ questionnaireType: val }).then(res => {
        if (res.resultCode == 200) {
          this.questionnaireList = res.data.map(x => ({ value: x.questionnaireId, text: x.questionnaireName }));
          if (careWay && careWay != null && careWay == 15871001) {
            this.formList[4].itemList = this.questionnaireList;
            // 修改时设置问卷模板下拉选中数据
            if (returnVisitContent && returnVisitContent != null) {
              this.formList[4].initialValue = parseInt(returnVisitContent);
            }
          }
        } else {
          this.$message.error('获取问卷失败!');
          return;
        }
      });
    },
    initCareObj(record, self) {
      let result = [];
      for (let i = 0; i < record.length; i++) {
        // 拼上INPUT基本信息
        let obj = {
          type: this.getInputType(record[i].dataType, record[i].confName),
          label: record[i].confName,
          fieldName: this.formatFiledName(record[i].fieldName, record[i].dataType),
          templateDealerId: record[i].templateDealerId,
          paramId: record[i].confId,
          dataType: record[i].dataType
        };
        if (record[i].value1 && record[i].value1 != '') {
          if (record[i].dataType === 10681001) {
            obj.initialValue = [];
          } else {
            obj.initialValue = '';
          }
        }
        // 如果是品牌选择框
        if (record[i].dataType === 10681004) {
          // 绑定变更事件
          obj.change = function(val) {
            getSeriesList(val, {}).then(res => {
              if (res.resultCode == 200) {
                self.seriesList = res.data.map(x => ({ value: x.seriesId, text: x.seriesName }));
                self.careObject[self.seriesIndex].itemList = self.seriesList;
              }
            });
          };
          obj.itemList = this.brandList;
        }
        // 如果是车系选择框
        if (record[i].dataType === 10681005) {
          this.seriesIndex = i;
          // 绑定变更事件
          obj.change = function(val) {
            let seriesId = self.careObject[self.seriesIndex].initialValue;
            getModelList(seriesId, val, {}).then(res => {
              if (res.resultCode == 200) {
                self.modelList = res.data.map(x => ({ value: x.modelId, text: x.modelName }));
                self.careObject[self.modelIndex].itemList = self.modelList;
              }
            });
          };
          obj.itemList = this.seriesList;
        }
        if (record[i].dataType === 10681008 || record[i].dataType === 10681009) {
          obj.format = 'MM-dd';
        }
        // 如果是车型选择框
        if (record[i].dataType === 10681006) {
          this.modelIndex = i;
          obj.itemList = this.modelList;
        }
        // TC_CODE选择框
        if (record[i].dataType === 10681003) {
          if (record[i].tagAttribute != '') {
            obj.itemList = this.createDictList(record[i].tagAttribute);
          } else {
            obj.itemList = [];
          }
        }
        result.push(obj);
      }
      this.careObject = result;
    },
    // 修改时获取关爱对象范围数据
    getInitialValue(value1, value2, fieldName, dataType) {
      if ('INTENT_LEVEL' === fieldName) {
        let nameArr = value1.split(',');
        let result = [];
        for (let i = 0; i < nameArr.length; i++) {
          result[i] = parseInt(nameArr[i]);
        }
        return result;
      }
      if (value2 && value2 != '' && (dataType == 10681008 || dataType == 10681009)) {
        return value1 + '-' + value2;
      }
      if (dataType === 10681001) {
        let result = [];
        result.push(value1 + ' 00:00:00');
        result.push(value2 + ' 00:00:00');
        return result;
      }
      if (dataType == 10681004) {
        this.brandId = value1;
      }
      var self = this;
      if (dataType == 10681005) {
        this.seriesId = value1;
        getSeriesList(this.brandId, {}).then(res => {
          if (res.resultCode == 200) {
            self.seriesList = res.data.map(x => ({ value: x.seriesId, text: x.seriesName }));
            self.careObject[self.seriesIndex].itemList = self.seriesList;
          }
        });
      }
      if (dataType == 10681006) {
        this.modelId = value1;
        getModelList(this.seriesId, this.brandId, {}).then(res => {
          if (res.resultCode == 200) {
            self.modelList = res.data.map(x => ({ value: x.modelId, text: x.modelName }));
            self.careObject[self.modelIndex].itemList = self.modelList;
          }
        });
      }
      return isNaN(value1) ? value1 : parseInt(value1);
    },
    // 生成关爱对象范围时获取fieldName
    formatFiledName(fieldName, val) {
      if (val === 10681001) {
        return fieldName + '|' + fieldName + '1';
      } else if (val === 10681009) {
        return fieldName + '1';
      } else {
        return fieldName;
      }
    },
    // 模板变更事件
    changeTemplateType(val) {
      this.formList[12].initialValue = '';
      this.formList[13].initialValue = '';
      this.formList[12].disabled = true;
      this.formList[13].disabled = true;
      this.formList[4].disabled = false;
      this.formList[4].initialValue = '';
      if (val === 15871001) {
        this.formList[4].itemList = this.questionnaireList;
      } else if (val === 15871002) {
        this.formList[4].itemList = this.smsTemplateList;
        this.formList[12].disabled = false;
        this.formList[13].disabled = false;
      } else {
        this.formList[4].disabled = true;
      }
    },
    // 过滤CODE下拉值
    filterDict(codeStr, dict) {
      if (codeStr && codeStr != '') {
        let dictList = this.createDictList(dict);
        let res = [];
        for (let i = 0; i < dictList.length; i++) {
          if (codeStr.indexOf(dictList[i].value) != -1) {
            res.push(dictList[i]);
          }
        }
        return res;
      }
      return '';
    },
    // 生成关爱对象范围时获取INPUT类型
    getInputType(val, name) {
      if ('潜客级别' === name) {
        return 'MULTIPLE_SELECT';
      } else if (val === 10681008 || val === 10681009) {
        return 'DATE';
      } else if (val === 10681002) {
        return 'TEXT_AREA';
      } else if (val === 10681003 || val === 10681004 || val === 10681005 || val === 10681006) {
        return 'SELECT';
      } else if (val === 10681007) {
        return 'INPUT';
      } else if (val === 10681001) {
        return 'RANGE_DATE';
      }
    },
    createCareEmp() {
      return [
        {
          type: 'RADIO',
          label: '分配规则',
          fieldName: 'careEmpType',
          selfCols: 2,
          itemList: this.createDictList('1595'),
          initialValue: 15951002,
          change: val => {
            if (val == 15951001) {
              this.careEmp[1].disabled = true;
              this.careEmp[1].initialValue = [];
            } else {
              this.careEmp[1].disabled = false;
            }
          }
        },
        {
          type: 'MULTIPLE_CHECKBOX',
          label: '关爱人员',
          fieldName: 'employeeIdList',
          disabled: false,
          selfCols: 4,
          itemList: []
        }
      ];
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    closeDialog(refresh) {
      if (refresh) {
        this.$emit('changeHandle', {});
      }
      this.$emit('close', false);
    },
    async saveDialog() {
      this.$refs.formPanel.SUBMIT_FORM();
      let data = [];
      if (this.saveData.specialHoliday && this.saveData.specialHoliday != '') {
        this.saveData.specialHoliday = this.saveData.specialHoliday.substring(0, 10);
        this.saveData.baseDateCode = 15901005;
      }
      this.careObject.forEach(obj => {
        let row = {};
        row.paramId = obj.paramId;
        row.paramValue1 = obj.initialValue;
        if (obj.dataType === 10681008 || obj.dataType === 10681009) {
          let dateStr2 = obj.initialValue;
          if (dateStr2.length > 5) {
            row.paramValue1 = dateStr2.substring(5, 7);
          } else {
            row.paramValue1 = dateStr2.substring(0, 2);
          }
          let dateStr = obj.initialValue;
          if (dateStr.length > 5) {
            row.paramValue2 = dateStr.substring(8, 10);
          } else {
            row.paramValue2 = dateStr.substring(3, 5);
          }
        }
        if (obj.dataType === 10681003) {
          row.paramValue1 = obj.initialValue.join(',');
        }
        if (obj.dataType === 10681001) {
          if (obj.initialValue && obj.initialValue != '' && obj.initialValue.length > 0) {
            row.paramValue1 = obj.initialValue[0].substring(0, 10);
            row.paramValue2 = obj.initialValue[1].substring(0, 10);
          }
        }
        row.templateDealerId = obj.templateDealerId;
        data.push(row);
      });
      this.saveData.careEmpType = this.careEmp[0].initialValue;
      this.saveData.employeeIdList = this.careEmp[1].initialValue;

      this.saveData.paramList = data;
      if (this.saveData !== null) {
        let res = {};
        if (this.type === 'add') {
          res = await addCareTaskList(this.saveData);
        }
        if (this.type === 'edit') {
          this.saveData.carePlanId = this.carePlanId;
          this.saveData.recordVersion = this.recordVersion;
          res = await editCareTaskList(this.saveData, this.empId);
        }
        if (res.resultCode === 200) {
          this.closeDialog(true);
        } else {
          this.$message(`${res.errMsg}`);
        }
      }
    }
  }
};
</script>

<style lang="less" scoped>
.dialog-form {
  width: 100%;
  margin: 0;
}

.el-checkbox-group .el-checkbox + .el-checkbox {
  margin: 0;
}

.box {
  border: 1px solid @borderColor;
  border-radius: @borderRadius;
  box-shadow: @boxShadow;
  padding: @modulePadding;
  margin-top: 20px;
}
</style>
